package com.ourcraft.informationcollectionsystem.service.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ourcraft.informationcollectionsystem.entity.Role;
import com.ourcraft.informationcollectionsystem.entity.User;
import com.ourcraft.informationcollectionsystem.mapper.RoleMapper;
import com.ourcraft.informationcollectionsystem.mapper.UserMapper;
import com.ourcraft.informationcollectionsystem.utils.authority.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

import static com.ourcraft.informationcollectionsystem.utils.Encryptor.encryptPassword;

/**
 * 用户模块调用的服务实现
 *
 * @author Z0136
 * @since 2023/10/29
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;

    /**
     * 用户进行登录
     *
     * @param id  登录账号
     * @param pwd 登录密码
     * @return 非空：登录成功的用户信息，空：登录失败
     */
    @Override
    public User login(Integer id, String pwd) {
        // 根据id和密码查询用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", id).eq("user_password", encryptPassword(pwd)).eq("user_status", true);
        User user = userMapper.selectOne(queryWrapper);
        if (user != null) {
            // 根据用户id查询角色
            QueryWrapper<Role> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("role_id", user.getRoleId());
            // 根据角色id查询权限
            Integer authority = roleMapper.selectOne(queryWrapper1).getRoleAuthority();
            user.setAuthority(authority);
            // 生成并设置用户Token
            user.setToken(JWTUtils.generateToken(user.getUserId(), authority));
//            System.out.println("a user login with authority " + authority);
        }
        return user;
    }

    /**
     * 根据Token获得用户信息
     *
     * @param token 用户token
     * @return 用户信息
     */
    @Override
    public User getUserInfo(String token) {
        // 根据token获得用户账户
        Integer userId = JWTUtils.getUserIdByToken(token);
        // 根据用户账号获取角色id
        Integer roleId = userMapper.selectById(userId).getRoleId();
        // 根据token获取用户权限
        Integer authority = JWTUtils.getAuthorityByToken(token);
        // 返回用户信息
        User user = new User();
        user.setUserId(userId);
        user.setToken(token);
        user.setRoleId(roleId);
        user.setAuthority(authority);
        return user;
    }

    @Override
    public Boolean changePassword(String oldPassword, String newPassword, Integer userId) {
        var user = userMapper.selectById(userId);
        if (!Objects.equals(oldPassword, user.getUserPassword()))
            return false;
        user.setUserPassword(newPassword);
        return userMapper.updateById(user) != 0;
    }
}
